"""
欢迎页面

应用的欢迎页面，展示概览信息和快速操作
"""

import customtkinter as ctk
from typing import Dict, List
import sys
from pathlib import Path

# 添加父目录到路径
sys.path.append(str(Path(__file__).parent.parent))

from ..themes import ModernTheme
from ..components import ModernButton, ModernCard, ModernProgressBar, StatusBadge
from ..layouts import GridLayout, CardGrid

# 导入数据库相关
try:
    from src.repositories.jianying_template_repository import JianyingTemplateRepository
    from src.core.dependency_injection import injector
    TEMPLATE_REPO_AVAILABLE = True
except ImportError:
    TEMPLATE_REPO_AVAILABLE = False

class WelcomePage(ctk.CTkFrame):
    """欢迎页面类"""
    
    def __init__(self, parent):
        super().__init__(parent, fg_color="transparent")

        # 初始化模板仓库
        self.template_repo = None
        if TEMPLATE_REPO_AVAILABLE:
            try:
                self.template_repo = injector.get(JianyingTemplateRepository)
            except Exception as e:
                print(f"无法获取模板仓库: {e}")

        # 创建主容器，添加padding和margin
        self.main_container = ctk.CTkFrame(self, fg_color="transparent")
        self.main_container.pack(fill="both", expand=True, padx=20, pady=16)

        self.create_page()
    
    def create_page(self):
        """创建页面内容"""
        # 创建滚动容器，设置自动隐藏滚动条
        self.scroll_frame = ctk.CTkScrollableFrame(
            self.main_container,
            fg_color="transparent",
            scrollbar_fg_color=ModernTheme.get_color('bg_tertiary'),
            scrollbar_button_color=ModernTheme.get_color('border_medium'),
            scrollbar_button_hover_color=ModernTheme.get_color('border_medium'),
            corner_radius=0
        )
        self.scroll_frame.pack(fill="both", expand=True, padx=0, pady=8)

        # 创建内容容器，添加内部padding
        self.content_container = ctk.CTkFrame(self.scroll_frame, fg_color="transparent")
        self.content_container.pack(fill="both", expand=True, padx=12, pady=12)

        # 绑定窗口大小变化事件来控制滚动条显示
        self.bind("<Configure>", self.on_frame_configure)
        self.after(500, self.update_scrollbar_visibility)

        # 欢迎标题
        self.create_welcome_header()

        # 数据概览卡片
        self.create_overview_cards()

        # 快速操作区域
        self.create_quick_actions()

    def get_template_statistics(self):
        """获取模板统计信息"""
        if not self.template_repo:
            return {
                'total_templates': 0,
                'total_video_segments': 0,
                'latest_scan': None
            }

        try:
            return self.template_repo.get_statistics()
        except Exception as e:
            print(f"获取模板统计信息失败: {e}")
            return {
                'total_templates': 0,
                'total_video_segments': 0,
                'latest_scan': None
            }

    def refresh_statistics(self):
        """刷新统计数据并更新显示"""
        try:
            # 重新创建概览卡片
            self.create_overview_cards()
        except Exception as e:
            print(f"刷新统计数据失败: {e}")

    def create_welcome_header(self):
        """创建欢迎标题"""
        header_frame = ctk.CTkFrame(self.content_container, fg_color="transparent")
        header_frame.pack(fill="x", pady=(0, ModernTheme.SIZES['spacing_xl']))

        # 主标题
        title = ctk.CTkLabel(
            header_frame,
            text="🎬 欢迎使用 MixVideo",
            font=ModernTheme.get_font('title'),
            text_color=ModernTheme.COLORS['primary']
        )
        title.pack(anchor="w")

        # 副标题
        subtitle = ctk.CTkLabel(
            header_frame,
            text="智能视频混剪平台 - 让创作更简单",
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_secondary')
        )
        subtitle.pack(anchor="w", pady=(ModernTheme.SIZES['spacing_xs'], 0))

        # 欢迎信息卡片
        welcome_card = ModernCard(header_frame)
        welcome_card.pack(fill="x", pady=(ModernTheme.SIZES['spacing_lg'], 0))

        welcome_text = ctk.CTkLabel(
            welcome_card.content_frame,
            text="✨ 欢迎回来！今天是创作的好日子。您可以开始新的混剪任务，管理模板库，或查看项目统计。",
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_primary'),
            wraplength=800,
            justify="left"
        )
        welcome_text.pack(anchor="w")

    def create_overview_cards(self):
        """创建数据概览卡片"""
        # 概览标题
        overview_title = ctk.CTkLabel(
            self.content_container,
            text="📊 数据概览",
            font=ModernTheme.get_font('heading'),
            text_color=ModernTheme.get_color('text_primary'),
            anchor="w"
        )
        overview_title.pack(fill="x", pady=(ModernTheme.SIZES['spacing_xl'], ModernTheme.SIZES['spacing_md']))

        # 创建网格布局
        overview_grid = GridLayout(self.content_container, columns=4)
        overview_grid.pack(fill="x", pady=(0, ModernTheme.SIZES['spacing_xl']))
        
        # 获取真实的统计数据
        template_stats = self.get_template_statistics()
        total_templates = template_stats.get('total_templates', 0)
        total_segments = template_stats.get('total_video_segments', 0)

        # 概览数据
        overview_data = [
            {
                "title": "📦 总模板数",
                "value": str(total_templates),
                "change": f"共{total_segments}个片段",
                "change_type": "info",
                "description": "数据库统计"
            }
        ]
        
        for data in overview_data:
            card = self.create_metric_card(overview_grid, data)
            overview_grid.add_widget(card)
    
    def create_metric_card(self, parent, data: Dict) -> ModernCard:
        """创建指标卡片"""
        card = ModernCard(parent)
        card.configure(height=120)
        
        # 标题
        title_label = ctk.CTkLabel(
            card.content_frame,
            text=data["title"],
            font=ModernTheme.get_font('body_sm'),
            text_color=ModernTheme.get_color('text_secondary'),
            anchor="w"
        )
        title_label.pack(fill="x")
        
        # 数值
        value_label = ctk.CTkLabel(
            card.content_frame,
            text=data["value"],
            font=ModernTheme.get_font('heading'),
            text_color=ModernTheme.get_color('text_primary'),
            anchor="w"
        )
        value_label.pack(fill="x", pady=(ModernTheme.SIZES['spacing_xs'], 0))
        
        # 变化和描述
        change_frame = ctk.CTkFrame(card.content_frame, fg_color="transparent")
        change_frame.pack(fill="x", pady=(ModernTheme.SIZES['spacing_sm'], 0))
        
        # 变化徽章
        change_badge = StatusBadge(
            change_frame,
            text=data["change"],
            status=data["change_type"]
        )
        change_badge.pack(side="left")
        
        # 描述
        desc_label = ctk.CTkLabel(
            change_frame,
            text=data["description"],
            font=ModernTheme.get_font('caption'),
            text_color=ModernTheme.get_color('text_secondary')
        )
        desc_label.pack(side="left", padx=(ModernTheme.SIZES['spacing_sm'], 0))
        
        return card
    
    def create_quick_actions(self):
        """创建快速操作区域"""
        # 快速操作标题
        actions_title = ctk.CTkLabel(
            self.scroll_frame,
            text="⚡ 快速操作",
            font=ModernTheme.get_font('heading'),
            text_color=ModernTheme.get_color('text_primary'),
            anchor="w"
        )
        actions_title.pack(fill="x", pady=(0, ModernTheme.SIZES['spacing_md']))
        
        # 操作按钮网格
        actions_grid = GridLayout(self.scroll_frame, columns=3)
        actions_grid.pack(fill="x", pady=(0, ModernTheme.SIZES['spacing_xl']))
        
        # 快速操作数据
        actions_data = [
            {
                "icon": "🎯",
                "title": "创建新任务",
                "description": "开始新的视频混剪项目",
                "action": self.create_new_task
            },
            {
                "icon": "📥",
                "title": "导入模板",
                "description": "添加新的混剪模板",
                "action": self.import_template
            },
            {
                "icon": "📊",
                "title": "查看报告",
                "description": "查看详细的统计报告",
                "action": self.view_reports
            }
        ]
        
        for action_data in actions_data:
            card = self.create_action_card(actions_grid, action_data)
            actions_grid.add_widget(card)
    
    def create_action_card(self, parent, data: Dict) -> ModernCard:
        """创建操作卡片"""
        card = ModernCard(parent)
        card.configure(height=140, cursor="hand2")
        
        # 图标
        icon_label = ctk.CTkLabel(
            card.content_frame,
            text=data["icon"],
            font=ctk.CTkFont(size=32),
            text_color=ModernTheme.COLORS['primary']
        )
        icon_label.pack(pady=(0, ModernTheme.SIZES['spacing_sm']))
        
        # 标题
        title_label = ctk.CTkLabel(
            card.content_frame,
            text=data["title"],
            font=ModernTheme.get_font('heading_sm'),
            text_color=ModernTheme.get_color('text_primary')
        )
        title_label.pack()
        
        # 描述
        desc_label = ctk.CTkLabel(
            card.content_frame,
            text=data["description"],
            font=ModernTheme.get_font('body_sm'),
            text_color=ModernTheme.get_color('text_secondary'),
            wraplength=200
        )
        desc_label.pack(pady=(ModernTheme.SIZES['spacing_xs'], 0))
        
        # 绑定点击事件
        def on_click(event):
            data["action"]()
        
        card.bind("<Button-1>", on_click)
        for child in card.winfo_children():
            child.bind("<Button-1>", on_click)
        
        return card
    
    
    def create_activity_item(self, parent, activity: Dict):
        """创建活动项"""
        item_frame = ctk.CTkFrame(parent, fg_color="transparent")
        item_frame.pack(fill="x", pady=(0, ModernTheme.SIZES['spacing_sm']))
        
        # 时间
        time_label = ctk.CTkLabel(
            item_frame,
            text=activity["time"],
            font=ModernTheme.get_font('caption'),
            text_color=ModernTheme.get_color('text_secondary'),
            width=80
        )
        time_label.pack(side="left")
        
        # 状态徽章
        status_badge = StatusBadge(
            item_frame,
            text="●",
            status=activity["status"]
        )
        status_badge.pack(side="left", padx=(ModernTheme.SIZES['spacing_sm'], 0))
        
        # 活动信息
        info_frame = ctk.CTkFrame(item_frame, fg_color="transparent")
        info_frame.pack(side="left", fill="x", expand=True, padx=(ModernTheme.SIZES['spacing_sm'], 0))
        
        action_label = ctk.CTkLabel(
            info_frame,
            text=activity["action"],
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_primary'),
            anchor="w"
        )
        action_label.pack(fill="x")
        
        detail_label = ctk.CTkLabel(
            info_frame,
            text=activity["detail"],
            font=ModernTheme.get_font('caption'),
            text_color=ModernTheme.get_color('text_secondary'),
            anchor="w"
        )
        detail_label.pack(fill="x")
    
    # 事件处理方法
    def create_new_task(self):
        """创建新任务"""
        print("创建新任务")
    
    def import_template(self):
        """导入模板"""
        print("导入模板")
    
    def view_reports(self):
        """查看报告"""
        print("查看报告")

    def on_frame_configure(self, event):
        """窗口大小变化时的回调"""
        if event.widget == self:
            # 延迟更新滚动条状态
            self.after(100, self.update_scrollbar_visibility)

    def update_scrollbar_visibility(self):
        """更新滚动条显示状态"""
        try:
            # 更新布局
            self.update_idletasks()
            self.scroll_frame.update_idletasks()

            # 简单的方法：设置滚动条样式使其在不需要时更不显眼
            # CustomTkinter的滚动条控制比较复杂，我们采用样式调整的方式

            # 检查内容是否需要滚动
            def check_and_update():
                try:
                    # 获取滚动框架的内部组件
                    for child in self.scroll_frame.winfo_children():
                        if hasattr(child, 'bbox'):
                            # 如果内容高度小于容器高度，调整滚动条样式
                            content_bbox = child.bbox("all")
                            if content_bbox:
                                content_height = content_bbox[3] - content_bbox[1]
                                container_height = self.scroll_frame.winfo_height()

                                if content_height <= container_height:
                                    # 内容不需要滚动，可以隐藏滚动条
                                    # 这里我们通过设置滚动条颜色为透明来"隐藏"它
                                    self.scroll_frame.configure(
                                        scrollbar_fg_color="transparent",
                                        scrollbar_button_color="transparent"
                                    )
                                else:
                                    # 需要滚动，恢复滚动条颜色
                                    self.scroll_frame.configure(
                                        scrollbar_fg_color=ModernTheme.get_color('bg_tertiary'),
                                        scrollbar_button_color=ModernTheme.get_color('border_medium')
                                    )
                            break
                except Exception:
                    pass

            # 延迟执行检查
            self.after(200, check_and_update)

        except Exception:
            pass
